package cn.huapu.power.energy.controller;

import cn.huapu.power.energy.bean.BaseEntity;
import cn.huapu.power.energy.service.BaseService;
import cn.huapu.power.energy.vo.Grid;
import cn.huapu.power.energy.vo.Page;
import cn.huapu.power.energy.vo.Ret;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 控制层的基本类，提供普通的增删改查等功能
 * @author hunter
 *
 * @param <T>
 */

public abstract class BaseController<T extends BaseEntity> {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	public abstract BaseService getService();
	
	@GetMapping("/data/{id}")
	public Ret data(@PathVariable(name="id",required=true)String id) {
		Ret r = new Ret();
		if(id != null) {
			r.setData(getService().get(id));
		}
		return r;
	}
	  
    @GetMapping("/dataGrid")
    public Grid dataGrid(@RequestBody T model, Page page) {
        if (page == null) {
            page = new Page();
        }       
        Grid grid = getService().queryListByPage(page, model);
        return grid;
    }
    
    @GetMapping("/dataList")
    public Ret dataList(@RequestBody T model) {
    	Ret r = new Ret();    	 
        List<T> list = getService().queryList(model);
        r.setData(list);
        return r;
    }   
    
    @DeleteMapping("/remove/{id}")   
    public Ret remove(@PathVariable(name="id",required=true)String mid) {
    	Ret ret = new Ret();
    	if(mid == null) {
    		ret.Error("参数为空", null);
    		return ret;
    	}
        try {
           int count = getService().remove(mid);
           if(count > 0) {
        	   ret.OK("删除成功", null); 
           }
           else {
        	   ret.Error("删除失败", mid);
           }
        } catch (Exception e) {
            logger.error("", e);
        }
        return ret;
    }
    
    @PostMapping("/update")   
    public Ret update(@RequestBody T model) {
    	Ret ret = new Ret();
        try {
            boolean action = (model.getMid() == null) ;
            int count = 0;
            if(action) {
            	count = getService().insert(model);
            }
            else {
            	count = getService().update(model);
            }
            if(count > 0) {
         	   ret.OK(action+"成功", model.getMid()); 
            }
            else {
         	   ret.Error(action+"失败", model.getMid());
            }
        } catch (Exception e) {
            logger.error("", e);           
        }
        return ret;
    }
   
}
